package com.zhx.app.social;

import com.zhx.StrException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;

import java.util.concurrent.TimeUnit;

/**
 *
 * 中间件 通过数据库保存用户的social信息
 * @author zhx
 * @create 2017-12-14 11:36
 **/
@Component
public class AppSignUpUtils {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    private UsersConnectionRepository usersConnectionRepository;

    /**
     * 定位 getConnectionFactory 根据 connectionData 可以构建出来一个connection
     */
    @Autowired
    private ConnectionFactoryLocator connectionFactoryLocator;

    /**
     * 保存用户的请求信息
     * @param webRequest
     * @param connectionData
     */
    public void saveConnectionData(WebRequest webRequest, ConnectionData connectionData){
        redisTemplate.opsForValue().set(getKey(webRequest),connectionData,10, TimeUnit.MINUTES);
    }

    public void doPostSignUp(String userId,WebRequest webRequest){
        String key = getKey(webRequest);
        if(!redisTemplate.hasKey(key)){
            throw new StrException("无法找到缓存的用户社交账号信息");
        }
        ConnectionData connectionData = (ConnectionData) redisTemplate.opsForValue().get(key);
        Connection<?> connection = connectionFactoryLocator.getConnectionFactory(connectionData.getProviderId())
                .createConnection(connectionData);
        usersConnectionRepository.createConnectionRepository(userId).addConnection(connection);

        redisTemplate.delete(key);
    }

    private String  getKey(WebRequest webRequest) {
        String deviceId = webRequest.getHeader("deviceId");
        if (StringUtils.isBlank(deviceId)) {
            throw new StrException("设备id参数不能为空");
        }
        return "zhx:security:social.connect." + deviceId;
    }
}
